﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using LiveNet.Authentication;
using LiveNet.Photos;

namespace LiveNet.Web
{
    public class LivePhotoHandler : IHttpHandler
    {
        #region IHttpHandler Members

        /// <summary>
        /// Gets a value indicating whether another request can use the <see cref="T:System.Web.IHttpHandler"/> instance.
        /// </summary>
        /// <value></value>
        /// <returns>true if the <see cref="T:System.Web.IHttpHandler"/> instance is reusable; otherwise, false.</returns>
        public bool IsReusable
        {
            get { return true; }
        }

        /// <summary>
        /// Enables processing of HTTP Web requests by a custom HttpHandler that implements the <see cref="T:System.Web.IHttpHandler"/> interface.
        /// </summary>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to the intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests.</param>
        public void ProcessRequest(HttpContext context)
        {
            string dat;
            string userId;
            string path = context.Request.QueryString["url"];

            // Get the authentication details for the request.
            IHttpAuthenticationObtainer obtainer = GetAuthenticationObtainer();
            obtainer.Get(context, out userId, out dat);

            LivePhotos m_photos = new LivePhotos(userId, dat, AuthenticationToken.DomainAuthenticationToken);
            Photo m_photo = m_photos.GetPhoto(path);
            context.Response.ContentType = "image/jpeg";

            WriteImageToStream(m_photo.GetImage(), context.Response.OutputStream);
        }

        private static IHttpAuthenticationObtainer GetAuthenticationObtainer()
        {
            string ta = Configuration.ConfigurationSectionHandler.Get().AuthenticationObtainerType;
            System.Configuration.TypeNameConverter d = new System.Configuration.TypeNameConverter();

            object o = Activator.CreateInstance((Type)d.ConvertFromString(ta));
            return (IHttpAuthenticationObtainer)o;
        }

        private static void WriteImageToStream(Image image, Stream stream)
        {
            if (image == null)
            {
                throw new ArgumentNullException("image");
            }

            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (stream.CanWrite)
            {
                using (MemoryStream imageStream = new MemoryStream())
                {
                    image.Save(imageStream, ImageFormat.Jpeg);
                    imageStream.Position = 0;

                    int b = imageStream.ReadByte();
                    while (b != -1)
                    {
                        stream.WriteByte((byte)b);
                        b = imageStream.ReadByte();
                    }
                }
            }
        }

        #endregion
    }
}
